<template>
  <UploadExce :on-success="upload" />
</template>

<script>
import { importEmployee } from '@/api/employees'
// import { formatDate } from '@/filters'
export default {
  methods: {
    async upload(data) {
    //   console.log(data)

      const newData = data.results.map((user) => {
        // console.log(user)
        return this.zh2en(user)
      })
      console.log(newData)
      // 发送数据
      await importEmployee(newData)
      this.$router.back()
    },
    zh2en(user) {
      // 定义空对象用来接收转换后的数据
      const newUser = {}

      //   console.log(user)
      // 变成英文
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      for (const key in user) {
        // console.log(userRelations[key])
        // 英文key拿出来给到新变量
        const En = userRelations[key]
        let value = user[key]
        // console.log(En)
        // this.newData[key] = En[key]
        // 然后user给到上面定义的一个空数组
        // user就是每个数组
        if (En === 'timeOfEntry' || En === 'correctionTime') {
          value = new Date(this.formatDate(value, '/'))
        }
        newUser[En] = value
        // console.log(newUser[En])
      }
      return newUser
    },

    // excel 专用
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>

<style>
</style>
